﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Objects;
using Course.DAO;
using Course.Models;

namespace Course.Controllers
{
    public class BackGroundController : BaseController
    {
        //
        // GET: /BackGround/

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 登陆(GET)
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {
            return View();
        }

        /// <summary>
        /// 登陆(Post)
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(FormCollection form)
        {
            string password = form["txtPassword"].Trim();
            string name = form["txtUserName"].Trim();
            AdminDAO adminDao = new AdminDAO();
            var admin = adminDao.GetOne(name);
            string jscontent = "";
            if (admin.Apassword == password)
            {
                Session["UserID"] = admin.AdminID;
                return RedirectToAction("Index");
            }
            else
            {
                // return Content("<script>alert('用户名或密码出错!请重新登陆!');window.history.back(-1);</script>");
                return MessageBack("用户名或密码出错!请重新登陆!");
            }
        }

        public ActionResult Content()
        {
            return View();
        }

        /// <summary>
        /// 管理分类(Get)
        /// </summary>
        /// <param name="p"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public ActionResult CategoryManager(int p = 1, int pagesize = 10)
        {
            ActionResult a = LoginSuccess();
            if (a != null)
            {
                return a;
            }
            CategoryDAO categoryDao = new CategoryDAO();
            var all = categoryDao.GetAll();
            //分页

            var query = all.ToPagedList(p - 1, pagesize);
            ViewData["all"] = query;
            return View();
        }

        /// <summary>
        /// 添加分类(Get)
        /// </summary>
        /// <returns></returns>
        public ActionResult CategoryAdd()
        {
            ActionResult a = LoginSuccess();
            if (a != null)
            {
                return a;
            }

            CategoryDAO categoryDao=new CategoryDAO();
            var allCate = categoryDao.GetAll();

            ViewData["allCate"] = allCate;
            return View();
        }

        /// <summary>
        /// 添加分类(Post)
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult CategoryAdd(FormCollection form)
        {
            CategoryDAO categoryDao = new CategoryDAO();

            string name = form["CategoryName"].Trim();
            int ownerNum;
            //判断排序号是否合法
            if (Int32.TryParse(form["OrderNum"].Trim(), out ownerNum) == true)
            {
                //判断是否存在
                if (categoryDao.GetOneByOrder(ownerNum) != null)
                {
                    // return Content("<script>alert('已存在此顺序!');window.history.back(-1);</script>");
                    return MessageBack("已存在此顺序");
                }
            }
            else
            {
                //return Content("<script>alert('添加失败,请检查数据!');window.history.back(-1);</script>");
                return MessageBack("添加失败,请检查数据");
            }
            //判断分类名称是否合法
            if (name.Length > 100 || name.Length == 0)
            {
                //return Content("<script>alert('分类名太长!');window.history.back(-1);</script>");
                return MessageBack("分类名不合法");
            }

            Category category = new Category();
            string isRoot="0";
            if (form["checkParent"] != null)
            {
                isRoot = form["checkParent"];
            }
            if(isRoot != "1")
            {
                int parentID = Int32.Parse(form["ddlCate"]);
                category.ParentID = parentID;
            }

            bool type = Boolean.Parse(form["ddlType"]);
            category.Statu = type;

            category.CName = name;
            category.OrderNum = ownerNum;



            if (categoryDao.AddOne(category) == true)
            {
                //return Content("<script>alert('添加成功!');window.location.href='CategoryManager'</script>");
                return MessageRedirect("添加成功", "CategoryManager");
            }
            else
            {
                // return Content("<script>alert('添加失败,请检查数据!');window.history.back(-1);</script>");
                return MessageBack("添加失败,请检查数据!");
            }
        }

        /// <summary>
        /// 修改分类(Get)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult CategoryEdit(int id)
        {
            ActionResult a = LoginSuccess();
            if (a != null)
            {
                return a;
            }
            CategoryDAO categoryDao = new CategoryDAO();

            var allCate = categoryDao.GetAll();

            ViewData["allCate"] = allCate;
            ViewData["one"] = categoryDao.GetOne(id);
            return View();
        }

        /// <summary>
        /// 修改分类(Post)
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult CategoryEdit(FormCollection form)
        {
            CategoryDAO categoryDao = new CategoryDAO();
            Category category = new Category();
            string name = form["CategoryName"].Trim();
            int ID = Int32.Parse(form["ID"]);

            category.CategoryID = ID;

            //判断名字是否合法
            if (name.Length > 100 || name.Length == 0)
            {
                // return Content("<script>alert('分类名太长!');window.history.back(-1);</script>");
                return MessageBack("分类名不合法");
            }
            category.CName = name;

            int orderNum;
            if (Int32.TryParse(form["OrderNum"].Trim(), out orderNum) == true)
            {
                Category c = categoryDao.GetOneByOrder(orderNum);

                if (c == null || c.CategoryID == category.CategoryID)
                {
                    category.OrderNum = orderNum;
                }
                else
                {
                    //return  Content("<script>alert('已存在此顺序!');window.history.back(-1);</script>");
                    return MessageBack("已存在此顺序");
                }
            }
            else
            {
                //return Content("<script>alert('修改失败,请检查数据!');window.history.back(-1);</script>");
                return MessageBack("修改失败,请检查数据");
            }

            string isRoot = "0";
            if (form["checkParent"] != null)
            {
                isRoot = form["checkParent"];
            }
            if (isRoot != "1")
            {
                int parentID = Int32.Parse(form["ddlCate"]);
                category.ParentID = parentID;
            }
            else
            {
                category.ParentID = null;
            }

            bool type = Boolean.Parse(form["ddlType"]);
            category.Statu = type;

            if (categoryDao.EditOne(category) == true)
            {
                // return Content("<script>alert('修改成功!');window.location.href='../CategoryManager'</script>");
                return MessageRedirect("修改成功!", "../CategoryManager");

            }
            else
            {
                //return Content("<script>alert('修改失败,请检查数据!');window.history.back(-1);</script>");
                return MessageBack("修改失败,请检查数据");
            }
        }

        /// <summary>
        /// 删除分类
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult CategoryDelete(int id)
        {
            ActionResult a = LoginSuccess();
            if (a != null)
            {
                return a;
            }

            CategoryDAO categoryDao = new CategoryDAO();
            if (categoryDao.DeleteOne(id) == true)
            {
                return RedirectToAction("CategoryManager");
            }
            else
            {
                return MessageBack("删除出错!");
            }
        }

        /// <summary>
        /// 删除文章
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ArticleDelete(int id)
        {
            ActionResult a = LoginSuccess();
            if (a != null)
            {
                return a;
            }

            ArticleDAO articleDao = new ArticleDAO();
            string reslut = articleDao.DeleteOne(id);

            if (reslut == "删除成功!")
            {
                //return MessageRedirect(reslut, "");
                //return Content("<script>alert('删除成功!');window.history.back(-1);</script>");
                return RedirectToAction("ArticleManager");

            }
            else
            {
                return MessageBack(reslut);
            }
        }

        /// <summary>
        /// 管理文章
        /// </summary>
        /// <param name="p"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public ActionResult ArticleManager(int p = 1, int pagesize = 10)
        {
            ActionResult a = LoginSuccess();
            if (a != null)
            {
                return a;
            }
            ArticleDAO articleDao = new ArticleDAO();

            var query = articleDao.GetAll();
            var all = query.ToPagedList(p - 1, pagesize);


            ViewData["all"] = all;
            return View();
        }


        /// <summary>
        /// 添加文章(Get)
        /// </summary>
        /// <returns></returns>
        public ActionResult ArticleAdd()
        {
            ActionResult a = LoginSuccess();
            if (a != null)
            {
                return a;
            }
            CategoryDAO categoryDao = new CategoryDAO();
            var categories = categoryDao.GetArticleCate();

            ViewData["categories"] = categories;
            return View();
        }

        /// <summary>
        /// 添加文章(Post)
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ArticleAdd(FormCollection form)
        {
            ArticleDAO articleDao = new ArticleDAO();
            Article article = new Article();
            string title = form["Title"].Trim();
            if (title.Length > 100 || title.Length == 0)
            {
                return MessageBack("标题名称不合法!");
            }

            string author = form["Author"].Trim();
            if (title.Length > 50)
            {
                return MessageBack("作者名过长! ");
            }

            string content = form["editor"];

            //   int ID = Int32.Parse(form["ID"]);
            int orderNum;
            if (Int32.TryParse(form["OrderNum"].Trim(), out orderNum) == true)
            {
                Article a = articleDao.GetOneByOrder(orderNum);
                if (a == null)
                {
                    article.OrderNum = orderNum;
                }
                else
                {
                    return MessageBack("已有此序号!");
                }
            }
            else
            {
                return MessageBack("顺序数有误!");
            }

            // article.ArticleID = ID;
            article.ATitle = title;
            article.Author = author;
            article.AContent = content;
            article.Atime = DateTime.Now;
            article.CategoryID = Int32.Parse(form["category"]);

            if (articleDao.AddOne(article) == true)
            {
                return MessageRedirect("添加成功!", "ArticleManager");
            }
            else
            {
                return MessageBack("添加失败,请检查数据");
            }
            return View();
        }

        /// <summary>
        /// 修改文章(GET)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ArticleEdit(int id)
        {
            ActionResult a = LoginSuccess();
            if (a != null)
            {
                return a;
            }
            ArticleDAO articleDao = new ArticleDAO();
            CategoryDAO categoryDao = new CategoryDAO();
            Article article = articleDao.GetOne(id);
            ViewData["one"] = article;
            ViewData["categories"] = categoryDao.GetArticleCate();

            return View();
        }

        /// <summary>
        /// 修改文章(POST)
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ArticleEdit(FormCollection form)
        {
            Article article = new Article();
            ArticleDAO articleDao = new ArticleDAO();


            string title = form["Title"].Trim();
            if (title.Length > 100 || title.Length == 0)
            {
                return MessageBack("标题格式有误!");
            }


            string author = form["Author"].Trim();
            if (author.Length > 50)
            {
                return MessageBack("作者名过长!");
            }

            string content = form["editor"];


            article.ArticleID = Int32.Parse(form["ID"]);
            int orderNum;
            if (Int32.TryParse(form["OrderNum"], out orderNum) == true)
            {
                Article a = articleDao.GetOneByOrder(orderNum);
                if (a == null || a.ArticleID == article.ArticleID)
                {
                    article.OrderNum = orderNum;
                }
                else
                {
                    return MessageBack("已有此序号!");
                }
            }
            else
            {
                return MessageBack("顺序数有误!");
            }


            article.ATitle = title;
            article.Author = author;
            article.AContent = content;
            article.CategoryID = Int32.Parse(form["category"]);

            if (articleDao.EditOne(article) == true)
            {
                // return Content("<script>alert('修改成功!');window.location.href='../CategoryManager'</script>");
                return MessageRedirect("修改成功!", "../ArticleManager");

            }
            else
            {
                //return Content("<script>alert('修改失败,请检查数据!');window.history.back(-1);</script>");
                return MessageBack("修改失败,请检查数据");
            }

        }

        /// <summary>
        /// 管理下载
        /// </summary>
        /// <param name="p"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public ActionResult DownloadManager(int p = 1, int pagesize = 10)
        {
            ActionResult a = LoginSuccess();
            if (a != null)
            {
                return a;
            }
            DownloadDAO downloadDao = new DownloadDAO();
            var query = downloadDao.GetAll().ToPagedList(p - 1, pagesize);

            ViewData["all"] = query;
            return View();
        }

        public ActionResult DownloadEdit(int id)
        {
            ActionResult a = LoginSuccess();
            if (a != null)
            {
                return a;
            }
            DownloadDAO downloadDao = new DownloadDAO();
            var query = downloadDao.GetOne(id);

            CategoryDAO categoryDao = new CategoryDAO();
            ViewData["categories"] = categoryDao.GetDownloadCate();

            ViewData["one"] = query;
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DownloadEdit(FormCollection form)
        {
            DownloadDAO downloadDao = new DownloadDAO();
            Download download = new Download();
            download.DownloadID = Int32.Parse(form["ID"]);

            //if (Request.Files.Count < 1)
            //{
            //    return MessageBack("请选择下载文件!");
            //}

            if (Request.Files.Count != 0)
            {
                if (Request.Files[0].FileName.Length == 0)
                {
                    return MessageBack("请选择下载文件");
                }
            }

            //string category = form["Category"].Trim();
            //if(category.Length>100||category.Length==0)
            //{
            //    return MessageBack("分类不合法!");
            //}
            //download.Statu = category;

            int cateID = Int32.Parse(form["ddlCate"]);
            download.CategoryID = cateID;

            string name = form["Name"].Trim();
            if (name.Length > 50 || name.Length == 0)
            {
                return MessageBack("名字不合法!");
            }
            download.DName = name;

            int orderNum;
            if (Int32.TryParse(form["OrderNum"].Trim(), out orderNum) == true)
            {
                Download d = downloadDao.GetOneByOrder(orderNum);
                if (d == null || d.DownloadID == download.DownloadID)
                {
                    download.OrderNum = orderNum;
                }
                else
                {
                    return MessageBack("已存在此序号!");
                }
            }
            else
            {
                return MessageBack("序号不合法!");
            }


            HttpPostedFileBase file = Request.Files[0];

            DateTime date = DateTime.Now;
            //时间串
            string f = date.ToString("yyyyMMddHHmmssff");
            //原文件名
            string str = file.FileName;
            //正式文件名
            string filename = f + str;

            //所在目录
            string destination = Server.MapPath("/Upload/");
            //完整地址(相对)
            string path = destination + filename;
            download.DUrl = path;
            file.SaveAs(path);

            if (downloadDao.EditOne(download) == true)
            {
                return MessageRedirect("修改成功!", "../DownloadManager");
            }
            else
            {
                return MessageBack("修改失败,请检查数据!");
            }
        }

        public ActionResult DownloadAdd()
        {
            ActionResult a = LoginSuccess();
            if (a != null)
            {
                return a;
            }

            CategoryDAO categoryDao=new CategoryDAO();
            ViewData["categories"] = categoryDao.GetDownloadCate();

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DownloadAdd(FormCollection form)
        {
            DownloadDAO downloadDao = new DownloadDAO();
            Download download = new Download();

            //if (Request.Files.Count == 0)
            //{
            //    return MessageBack("请选择下载文件!");
            //}

            if(Request.Files.Count!=0)
            {
                if(Request.Files[0].FileName.Length==0)
                {
                    return MessageBack("请选择下载文件");
                }
            }



            int cateID = Int32.Parse(form["ddlCate"]);
            download.CategoryID = cateID;
    

            string name = form["Name"].Trim();
            if (name.Length > 50 || name.Length == 0)
            {
                return MessageBack("名字不合法!");
            }
            download.DName = name;

            int orderNum;
            if (Int32.TryParse(form["OrderNum"].Trim(), out orderNum) == true)
            {
                Download d = downloadDao.GetOneByOrder(orderNum);
                if (d == null)
                {
                    download.OrderNum = orderNum;
                }
                else
                {
                    return MessageBack("已存在此序号!");
                }
            }
            else
            {
                return MessageBack("序号不合法!");
            }


            HttpPostedFileBase file = Request.Files[0];

            DateTime date = DateTime.Now;
            //时间串
            string f = date.ToString("yyyyMMddHHmmssff");
            //原文件名
            string str = file.FileName;
            //正式文件名
            string filename = f + str;

            //所在目录                                                                                                             
            string destination = Server.MapPath("/Upload/");
            //完整地址(相对)
            string path = destination + filename;
            download.DUrl = path;
            file.SaveAs(path);

            if (downloadDao.AddOne(download) == true)
            {
                return MessageRedirect("添加成功!", "DownloadManager");
            }
            else
            {
                return MessageBack("添加失败,请检查数据!");
            }
        }


        public ActionResult DownloadDelete(int id)
        {
            ActionResult a = LoginSuccess();
            if(a!=null)
            {
                return a;
            }

            DownloadDAO downloadDao=new DownloadDAO();
            if(downloadDao.DeleteOne(id)==true)
            {
                return RedirectToAction("DownloadManager");
            }
            else
            {
                return MessageBack("删除出错!");
            }

        }

        public ActionResult CateDownloadManager()
        {
            return View();
        }
    }
}
